<?php
declare(strict_types=1);
// 导航高亮显示
function nav_active(string $nav, string $class = ' class="active"'): string
{
    if (str_starts_with($nav, '@')) {
        $nav = substr($nav, 1);
        return ($nav == get_action()) ? $class : '';
    }
    return ($nav == get_controller()) ? $class : '';
}
// 获取用户头像
function get_avatar(string $avatar = '', string $qq = ''): string
{
    if (!empty($avatar)) {
        return $avatar;
    }
    if (!empty($qq)) {
        return 'http://q1.qlogo.cn/g?b=qq&nk='.$qq.'&s=100&t='.time();
    }
    return __STATIC__.'/img/avatar.png';
}

// 获取随机缩略图
function rand_thumb(string $url, int $i): string
{
    if (!empty($url)) {
        return $url;
    }
    if ($i > 40) {
        $i = $i % 40;
    }
    return __STATIC__ . '/img/thumb/' . $i . '.jpg';
}

// form-select生成
function form_select(string $name, $options, $selected = '', string $attr = ''): string
{
    if (!is_array($options)) {
        $options = str_to_array($options);
    }
    if (!empty($attr)) {
        $attr = ' ' . clear_html($attr);
    }
    $selected = is_array($selected) ? $selected : explode(',', strval($selected));
    $select = '<select name="' . $name . '"' . $attr . '>' . "\n";
    foreach ($options as $k => $v) {
        $select .= "\t<option value=\"{$k}\"" . (in_array($k, $selected) ? ' selected="selected"' : '') . ">{$v}</option>\n";
    }
    return $select . "</select>\n";
}

// form-radio生成
function form_radio(string $name, $options, $selected = '', string $attr = '', bool $is_label = true): string
{
    if (!is_array($options)) {
        $options = str_to_array($options);
    }
    if (!empty($attr)) {
        $attr = ' ' . clear_html($attr);
    }
    $radio = '';
    foreach ($options as $k => $v) {
        if ($is_label) {
            $radio .= '<label' . $attr . '><input type="radio" name="' . $name . '" value="' . $k . '"' . ($k == $selected ? ' checked="checked"' : '') . ' /> ' . $v . '</label>' . "\n";
        } else {
            $radio .= '<input type="radio" name="' . $name . '" value="' . $k . '" title="' . $v . '"' . ($k == $selected ? ' checked="checked"' : '') . ' />';
        }
    }
    return $radio;
}

// 封面上传表单属性
function pic_attr(string $url = ''): array
{
    $data = [
        'img' => ' style="display:none"',
        'span' => '',
    ];
    if (!empty($url)) {
        $data['img'] = ' src="'.$url.'"';
        $data['span'] = ' style="display:inline"';
    }
    return $data;
}

// 获取表数据上下篇
function get_related(int $id, string $table, array $options = []): array
{
    $data = widget('common.related')->get($table, $options);
    return get_prev_next($id, $data);
}